<?php
/**
 * @version		$Id: migrator.php 25 2010-09-08 15:16:11Z joomlaworks $
 * @package		K2mart
 * @author    JoomlaWorks http://www.joomlaworks.gr
 * @copyright	Copyright (c) 2006 - 2010 JoomlaWorks, a business unit of Nuevvo Webware Ltd. All rights reserved.
 * @license		Commercial - This code cannot be redistributed without permission from Nuevvo Webware Ltd.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class K2martModelMigrator extends JModel {

	function import() {

		$mainframe = &JFactory::getApplication();
		jimport('joomla.filesystem.file');
		if(!JFile::exists(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'admin.k2.php')){
			return false;
		}
		set_time_limit(0);
		ini_set('memory_limit', '512M');
		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
		JLoader::register('Upload', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'class.upload.php');
		$user = &JFactory::getUser();
		$date = &JFactory::getDate();
		$now = $date->toMySQL();
		$db = &JFactory::getDBO();
		$params = &JComponentHelper::getParams('com_k2');
				
		//Get K2 default category parameters
		$xml = new JSimpleXML;
		$xml->loadFile(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'models'.DS.'category.xml');
		$categoryParams = new JParameter('');

		foreach ($xml->document->params as $paramGroup) {
			foreach ($paramGroup->param as $param) {
				if ($param->attributes('type') != 'spacer') {
					$categoryParams->set($param->attributes('name'), $param->attributes('default'));
				}
			}
		}

		//Handle the K2 root category
		$rootCatid = JRequest::getInt('catid');
		if(!$rootCatid){
			$RootK2Category = &JTable::getInstance('K2Category', 'Table');
			$RootK2Category->name = JRequest::getString('categoryName');
			$RootK2Category->published = 1;
			$RootK2Category->access = 0;
			$RootK2Category->trash = 0;
			$RootK2Category->parent = 0;
			$RootK2Category->ordering = $RootK2Category->getNextOrder('parent=0');
			//Set image params
			$params->merge($categoryParams);
			$RootK2Category->params = $categoryParams->toString();
			$RootK2Category->check();
			$RootK2Category->store();
			$categoryParams->set('inheritFrom', $RootK2Category->id);
			$parent = $RootK2Category->id;
		}
		else {
			$categoryParams->set('inheritFrom', $rootCatid);
			$parent = $rootCatid;
			//Set image params
			$query = "SELECT * FROM #__k2_categories WHERE id=".$rootCatid;
            $db->setQuery($query, 0, 1);
            $masterCategory = $db->loadObject();
            $cparams = new JParameter($masterCategory->params);
			$params->merge($cparams);
		}

		$categoryParams = $categoryParams->toString();
		
		

		//Get K2 default item params
		$xml = new JSimpleXML;
		$xml->loadFile(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'models'.DS.'item.xml');
		$itemParams = new JParameter('');

		foreach ($xml->document->params as $paramGroup) {
			foreach ($paramGroup->param as $param) {
				if ($param->attributes('type') != 'spacer') {
					$itemParams->set($param->attributes('name'), $param->attributes('default'));
				}
			}
		}
		$itemParams = $itemParams->toString();

		//Include Virtuemart classes
		global $ps_product, $ps_product_category;
		require_once(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'virtuemart_parser.php');
		include_class('product');
		include_class('category');
		$vmDB = new ps_DB;

		//Get virtuemart categories
		$rows = $ps_product_category->getCategoryTreeArray(JRequest::getBool('ignoreUnpublished'));
		$result = $ps_product_category->sortCategoryTreeArray($rows);
		$IDs = $result['id_list'];
		$depth = $result['depth_list'];
		$categories = array();
		foreach($IDs as $key=>$value){
			$rows[$value]['depth'] = $depth[$key];
			$categories[]=$rows[$value];
		}

		//Sort categories by depth descending
		function sortByDepth($x, $y) {
			if ( $x['depth'] == $y['depth'] )
			return 0;
			else if ( $x['depth'] < $y['depth'] )
			return 1;
			else
			return -1;
		}
		usort($categories, 'sortByDepth');

		//Handle data
		$K2CategoriesXref = array();
		$K2CreatedCategories = array();
		$VMProcessedProducts = array();
		foreach($categories as $key=>$category){
			$K2Category = &JTable::getInstance('K2Category', 'Table');
			$K2Category->name = $category['category_name'];
			$K2Category->description = $category['category_description'];
			$K2Category->published = ($category['category_publish']=='Y')?1:0;
			$K2Category->access = 0;
			$K2Category->trash = 0;
			$K2Category->ordering = $category['list_order'];
			$K2Category->parent = $category['category_parent_id'];
			$K2Category->image = $ps_product_category->get_field($category['category_child_id'], 'category_full_image');
			if(!is_string($K2Category->image)){
				$K2Category->image = NULL;
			}
			$K2Category->params = $categoryParams;
			$K2Category->check();
			$K2Category->store();
			if (JFile::exists(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'shop_image'.DS.'category'.DS.$K2Category->image)) {
				JFile::copy(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'shop_image'.DS.'category'.DS.$K2Category->image, JPATH_SITE.DS.'media'.DS.'k2'.DS.'categories'.DS.$K2Category->image);
			}
			$object = new JObject;
			$object->set('K2Category', $K2Category->id);
			$object->set('VMCategory', $category['category_child_id']);
			$K2CategoriesXref[]=$object;
			$K2CreatedCategories[]=$K2Category->id;

			//Create category tag
			$K2Tag = &JTable::getInstance('K2Tag', 'Table');
			$K2Tag->name = $category['category_name'];
			$K2Tag->published = ($category['category_publish']=='Y')?1:0;
			$K2Tag->check();
			$K2Tag->store();


			//Get category products
			$query = "SELECT product.*, category.category_id FROM #__{vm}_product AS product
			LEFT JOIN #__{vm}_product_category_xref AS category ON product.product_id = category.product_id
			WHERE ";
			if($key==0){
				$query.=" (category.category_id = ".$category['category_child_id']." OR category.category_id = 0)";
			}
			else {
				$query.=" category.category_id = ".$category['category_child_id'];
			}
			if(JRequest::getBool('ignoreUnpublished')){
				$query.=" AND product.product_publish = 'Y'";
			}
			$vmDB->setQuery($query);
			$products = $vmDB->loadObjectList();

			foreach($products as $product){

				if(!in_array($product->product_id, $VMProcessedProducts)) {
					$K2Item = &JTable::getInstance('K2Item', 'Table');
					$K2Item->title = $product->product_name;
					$K2Item->alias = $product->product_name;
					if($product->category_id==0){
						$K2Item->catid = $parent;
					}
					else {
						$K2Item->catid = $K2Category->id;
					}
					$K2Item->trash = 0;
					$K2Item->published = ($product->product_publish=='Y')?1:0;
					$K2Item->introtext = $product->product_s_desc;
					$K2Item->fulltext = $product->product_desc;
					$K2Item->created = $now;
					$K2Item->created_by = $user->id;
					$K2Item->access = 0;
					$K2Item->ordering = $K2Item->getNextOrder("catid = ".$K2Item->catid);
					$K2Item->hits = 0;
					$K2Item->params = $itemParams;
					$K2Item->check();
					$K2Item->store();


					//Save image
					if (JRequest::getBool('proccessImages') && JFile::exists(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'shop_image'.DS.'product'.DS.$product->product_full_image)) {

						$handle = new Upload(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'shop_image'.DS.'product'.DS.$product->product_full_image);
						$handle->allowed = array('image/*');
						
						//Original image
						$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'src';
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = 100;
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = md5("Image".$K2Item->id);
						$handle->Process($savepath);

						$filename = $handle->file_dst_name_body;
						$savepath = JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache';

						//XLarge image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_XL';
						if (JRequest::getInt('itemImageXL')) {
							$imageWidth = JRequest::getInt('itemImageXL');
						} else {
							$imageWidth = $params->get('itemImageXL', '800');
						}
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);

						//Large image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_L';
						if (JRequest::getInt('itemImageL')) {
							$imageWidth = JRequest::getInt('itemImageL');
						} else {
							$imageWidth = $params->get('itemImageL', '600');
						}
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);

						//Medium image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_M';
						if (JRequest::getInt('itemImageM')) {
							$imageWidth = JRequest::getInt('itemImageM');
						} else {
							$imageWidth = $params->get('itemImageM', '400');
						}
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);

						//Small image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_S';
						if (JRequest::getInt('itemImageS')) {
							$imageWidth = JRequest::getInt('itemImageS');
						} else {
							$imageWidth = $params->get('itemImageS', '200');
						}
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);

						//XSmall image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_XS';
						if (JRequest::getInt('itemImageXS')) {
							$imageWidth = JRequest::getInt('itemImageXS');
						} else {
							$imageWidth = $params->get('itemImageXS', '100');
						}
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);

						//Generic image
						$handle->image_resize = true;
						$handle->image_ratio_y = true;
						$handle->image_convert = 'jpg';
						$handle->jpeg_quality = $params->get('imagesQuality');
						$handle->file_auto_rename = false;
						$handle->file_overwrite = true;
						$handle->file_new_name_body = $filename.'_Generic';
						$imageWidth = $params->get('itemImageGeneric', '300');
						$handle->image_x = $imageWidth;
						$handle->Process($savepath);


							
					}
					$VMProcessedProducts[] = $product->product_id;
				}

				//Insert tag reference
				$query = "INSERT INTO #__k2_tags_xref (`id`, `tagID`, `itemID`) VALUES (NULL, {$K2Tag->id}, {$K2Item->id})";
				$db->setQuery($query);
				$db->query();

				//Insert K2mart reference
				$query = "INSERT INTO #__k2mart (`id`, `productID`, `itemID`) VALUES (NULL, {$product->product_id}, {$K2Item->id})";
				$db->setQuery($query);
				$db->query();
			}
		}

		//Fix category relationships
		foreach($K2CategoriesXref as $ref){
			$query = "UPDATE #__k2_categories SET parent = {$ref->K2Category} WHERE parent = {$ref->VMCategory} AND id IN (".implode(',', $K2CreatedCategories).")";
			$db->setQuery($query);
			$db->query();
		}
		$query = "UPDATE #__k2_categories SET parent = {$parent} WHERE parent = 0 AND id IN (".implode(',', $K2CreatedCategories).")";
		$db->setQuery($query);
		$db->query();
	
	}
}
